<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 17-7-27
 * Time: 下午4:48
 */

namespace app\controller;


use app\model\Admin;
use app\model\FConfigList;
use app\model\OrderLog;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;


/**
 * @property array resultdata
 * @property SysRole Role
 * @property false|\PDOStatement|string|\think\Collection role_list
 * @property string is_agent
 * @property int admin_id
 * @property string admin_name
 * @property int agent_id
 * @property string admin_real_name
 * @property bool is_ajax
 * @property array admin_menu_list
 * @property false|\PDOStatement|string|\think\Collection menu_list
 * @property  array dispatch_module
 * @property string|Request controller
 * @property string|Request action
 * @property OrderLog OrderLog
 * @property string recharge_url
 * @property Admin SysUser
 * @property FConfigList FConfigList
 * @property array config_list
 * @property string host
 * @property int company_id
 * @property string admin_open_id
 * @property string url
 * @property mixed ip
 * @property string domain
 */
class CommonController extends Controller
{
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        Session::start();
        $SysMenu = new \app\model\AdminMenu();
        $this->url = $request->url(true);
        $this->ip = $request->ip();
        $this->domain =  $request->domain();
        $this->SysUser = new Admin();
        $this->FConfigList = new FConfigList();
        $this->menu_list = $SysMenu->order("sort asc,id asc")->select();

        $this->Role = new \app\model\AdminRole();
        $this->role_list = $this->Role->select();
        $this->role_list = make_array_key($this->role_list,"id",true);





        $this->OrderLog = new OrderLog();
        $this->resultdata = ["error"=>1,"msg"=>"未知错误","data"=>[]];
        $this->admin_id = 0;
        $this->agent_id = 0;
        $this->company_id = 0;
        $this->admin_name = "";
        $this->admin_open_id = "";
        $this->admin_menu_list = [];
        $this->is_ajax = $request->isAjax();
        $this->controller = strtolower($request->controller());
        $this->action = $request->action();
        $this->host = $request->domain();

        $this->check_login();

        $this->assign("version","0.0.7");
        $this->assign("NOW_TIME",NOW_TIME);
        $this->assign("ADMIN_ID",$this->admin_id);
        $this->assign("ADMIN_NAME",$this->admin_name);
        $this->assign("ADMIN_REAL_NAME",$this->admin_name);
        $this->assign("ADMIN_OPEN_ID",$this->admin_open_id);
        $config_list = $this->FConfigList->where(["status"=>0])->field("name,value")->select();
        $config_list = make_array_key($config_list,"name",true);
        $config_list["USER_REBATE"]["value"] = !empty($config_list["USER_REBATE"]["value"])?json_decode($config_list["USER_REBATE"]["value"],true):[];
        $this->config_list = $config_list;

        $this->assign("config_list",$config_list);
        $menu_list = [];

        foreach ($this->menu_list as $key=>$val)
        {
            if(in_array($val["id"],$this->admin_menu_list)||in_array("all",$this->admin_menu_list))
            {
                $menu_list[] = $val->toArray();
            }
        }

        $menu_list = array_to_tree($menu_list);
//        print_r($menu_list);

        $this->assign("menu_list",$menu_list);
        $this->check_role();

        $this->admin_log();
//        $this->check_order();
//        print_r($this->agent_id);
//        $this->agent_id = 29;



    }

    function order_log($order_no,$remark)
    {
        $this->OrderLog->insert(["order_no"=>$order_no,"remark"=>$remark,"admin_id"=>$this->admin_id,"ctime"=>NOW_TIME]);
    }

    /**
     * @param $msg
     * @param int $code
     * @throws Exception
     */
    function E($msg, $code=0)
    {
        throw new Exception($msg,$code);
    }
    function check_role()
    {
        if($this->controller == "index" && $this->action =="index")
        {
            if(empty($this->admin_id))
            {
                $this->redirect("/login");
                return false;
            }


        }
        foreach ($this->menu_list as $key=>$val)
        {
            $link = $val["link"];
            $module = explode("/",$link);
            $module[0] = !empty($module[0])?$module[0]:"";
            $module[1] = !empty($module[1])?strtolower($module[1]):"index";
            $module[2] = !empty($module[2])?strtolower($module[2]):"index";
            if($module[1] == $this->controller &&$module[2] == $this->action)
            {
                if(empty($this->admin_id))
                    $this->ErrorBack("请重新登录","/login");
                if(!empty($link)&&!in_array($val["id"],$this->admin_menu_list)&&!in_array("all",$this->admin_menu_list))
                {

                    $this->ErrorBack("你没有权限");
                }

            }

        }
    }
    function ErrorBack($msg,$url="")
    {
        if($this->is_ajax)
        {
            $this->resultdata["msg"] = $msg;
            $this->resultdata["url"] = $url;
            echo json_encode($this->resultdata);
            exit();
        }else{
            $this->error($msg,$url);
        }
    }
    function check_login()
    {
        if(!empty($_SESSION["admin_info"]))
        {
            $this->is_agent = !empty($_SESSION["admin_info"]["is_agent"])?$_SESSION["admin_info"]["is_agent"]:"n";
            $this->admin_id = !empty($_SESSION["admin_info"]["admin_id"])?$_SESSION["admin_info"]["admin_id"]:0;
            $this->admin_name = !empty($_SESSION["admin_info"]["admin_name"])?$_SESSION["admin_info"]["admin_name"]:"";
            $this->agent_id = !empty($_SESSION["admin_info"]["agent_id"])?$_SESSION["admin_info"]["agent_id"]:0;
            $this->admin_real_name = !empty($_SESSION["admin_info"]["admin_real_name"])?$_SESSION["admin_info"]["admin_real_name"]:0;
            $this->admin_menu_list = !empty($_SESSION["admin_info"]["admin_menu_list"])?$_SESSION["admin_info"]["admin_menu_list"]:[];
        }
        if($this->admin_id)
        {
            $info = $this->SysUser->where(["id"=>$this->admin_id])->find();
            if(!empty($info))
            {
                $this->agent_id = $info["agent_id"];
                $this->admin_open_id = $info["open_id"];
                $this->admin_name = $info["user_name"];
                $this->admin_real_name = $info["real_name"];
                $this->company_id = $info["company_id"];
                $role_list = explode(",",$info["role_list"]);
                $admin_menu_list = [];
                foreach ($role_list as $key=>$val)
                {
                    if(!empty($this->role_list[$val]))
                    {
                        $admin_menu_list = array_merge($admin_menu_list,explode(",",$this->role_list[$val]["menu_list"]));
                    }
                }
                $this->admin_menu_list  = $admin_menu_list;
            }

        }
    }

    function admin_log()
    {

        if($this->admin_id)
        {
            if($this->controller == "adminlist"&&$this->action=="ajax_set_password")
            {
                $module = $this->controller.".".$this->action;
                $content = json_encode($_REQUEST);
                $ip = $this->request->ip();
                Db::table('f_admin_log')->insert(["module"=>$module,"content"=>$content,"admin_id"=>$this->admin_id,"ip"=>$ip]);
            }else{
                foreach ($this->menu_list as $key=>$val)
                {
                    $link = $val["link"];
                    $module = explode("/",$link);
                    $module[0] = !empty($module[0])?$module[0]:"";
                    $module[1] = !empty($module[1])?strtolower($module[1]):"index";
                    $module[2] = !empty($module[2])?strtolower($module[2]):"index";
                    if($module[1] == $this->controller &&$module[2] == $this->action &&!empty($val["is_log"]))
                    {
                        $module = $this->controller.".".$this->action;
                        $content = json_encode($_REQUEST);
                        $ip = $this->request->ip();
                        Db::table('f_admin_log')->insert(["module"=>$module,"content"=>$content,"admin_id"=>$this->admin_id,"ip"=>$ip]);

                    }

                }
            }


        }
    }

    function ajaxResult()
    {
        echo json_encode($this->resultdata);
        exit();
    }


}